package com.gitee.ywj1352.算法.week05;

public class

最长回文子串 {


    // dp[i][j] = (s[i] == s[j]) && (dp[i-1]dp[j-1])
    public static String longestPalindrome(String s) {
        int length = s.length();
        boolean[][] dp = new boolean[length][length];

        for (int i = 0; i < length; i++) {
            dp[i][i] = true;
        }
        int maxLen = 0;
        int start = 0;
        char[] chars = s.toCharArray();
        for (int i = 1; i < length; i++) {
            for (int j = 0; j < i; j++) {
                dp[i][j] = (chars[i] == chars[j]) && dp[i - 1][j];
                if (dp[i][j] && i - j + 1 > maxLen) {
                    maxLen = i - j + 1;
                    start = i;
                }
            }
        }

        return s.substring(start, start + maxLen);
    }

    public static String longestPalindrome2(String s) {
        if (s.length() ==0){
            return "";
        }

        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = check(s, i, i);
            int len2 = check(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }

        return s.substring(start, end + 1);
    }


    public static int check(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }


    public static void main(String[] args) {
        System.out.println(longestPalindrome2("abaab"));
    }

}
